package ro.ubbcluj.adm.twitter.client;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * This class initiates connections to the Twitter services, performing the
 * OAuth dance.
 */
public class TwitterConnector {

	/**
	 * Consumer keys for tweet4adm registered to Twitter Apps.
	 */
	private static final String CONSUMER_KEY = "QMPscXSU3BkuztZch4kVPw";
	private static final String CONSUMER_SECRET = "Baj9OpsWWctOig0oGYIRqnOWG1NK5GBUyhBjCfGzY";

	private Context context;
	private TwitterConnectorListener listener;

	public TwitterConnector(Context context) {
		this.context = context;
	}

	public void setListener(TwitterConnectorListener listener) {
		this.listener = listener;
	}

	/**
	 * Initiates the connection process. If user is not already logged in,
	 * starts the OAuth dance. Connection is received via listener.
	 */
	public void openTwitterConnection() {
		Twitter twitterConnection = new TwitterFactory().getInstance();
		twitterConnection.setOAuthConsumer(TwitterConnector.CONSUMER_KEY, TwitterConnector.CONSUMER_SECRET);
		AccessToken savedAccessToken = PreferencesStorage.loadAccessTokenFromPreferences(context);
		if (savedAccessToken != null) {
			twitterConnection.setOAuthAccessToken(savedAccessToken);
			if (listener != null) {
				listener.onConnectionSuccessful(twitterConnection);
			}
		} else {
			initiateConnection(twitterConnection);
		}
	}

	/**
	 * Starts OAuth dance.
	 */
	private void initiateConnection(Twitter twitterConnection) {
		try {
			RequestToken requestToken = twitterConnection.getOAuthRequestToken("");
			showWebViewDialog(twitterConnection, requestToken);
		} catch (TwitterException e) {
			if (listener != null) {
				listener.onException(e);
			}
		}
	}

	/**
	 * Creates and shows the web page used to authenticate and authorize the
	 * user to Twitter.
	 */
	private void showWebViewDialog(final Twitter twitterConection, final RequestToken requestToken) {
		LinearLayout container = new LinearLayout(context);
		container.setMinimumWidth(200);
		container.setMinimumHeight(320);
		container.bringToFront();
		WebView webView = new WebView(context);
		webView.setMinimumWidth(200);
		webView.setMinimumHeight(380);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient());
		webView.loadUrl(requestToken.getAuthorizationURL());
		container.addView(webView);
		Builder webDialog = new AlertDialog.Builder(context);
		webDialog.setView(container).setTitle("Web Settings")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						twitterPinCodeDialog(twitterConection, requestToken);
						dialog.dismiss();
					}

				}).show();
	}

	/**
	 * Creates and shows the pin code dialog.
	 */
	private void twitterPinCodeDialog(final Twitter twitterConnection, final RequestToken requestToken) {
		LinearLayout pinHolder = new LinearLayout(context);
		pinHolder.setGravity(Gravity.CENTER);
		final EditText editPinCode = new EditText(context);
		editPinCode.setGravity(Gravity.CENTER);
		editPinCode.setWidth(200);
		pinHolder.addView(editPinCode);

		Builder pinBuilder = new AlertDialog.Builder(context);
		pinBuilder.setView(pinHolder).setTitle("Twitter Pin Code Entry")
				.setMessage("Please enter displayed twitter code into the field")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (editPinCode.getText().toString() != null && !editPinCode.getText().toString().equals("")) {
							try {
								AccessToken accessToken = twitterConnection.getOAuthAccessToken(requestToken,
										editPinCode.getText().toString());
								PreferencesStorage.storeAccessTokenToPreferences(context, accessToken);
								if (listener != null) {
									listener.onConnectionSuccessful(twitterConnection);
								}
							} catch (TwitterException e) {
								if (listener != null) {
									listener.onException(e);
								}
							}
						} else {
							Toast.makeText(context, "Pin code is required", Toast.LENGTH_SHORT).show();
							dialog.dismiss();
							twitterPinCodeDialog(twitterConnection, requestToken);
						}

					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (listener != null) {
							listener.onConnectionAborted();
						}
					}

				}).show();
	}
}
